<template>
  <div class="user-management-container">
    <vab-query-form>
      <vab-query-form-left-panel :span="6">
        <el-button icon="el-icon-plus" type="primary" @click="handleEdit">
          添加
        </el-button>
      </vab-query-form-left-panel>
      <vab-query-form-right-panel :span="18">
        <el-form :inline="true" :model="queryForm" @submit.native.prevent>
          <el-form-item label="账号">
            <el-input
              v-model.trim="queryForm.condition.account"
              clearable
              placeholder="请输入账号"
            />
          </el-form-item>
          <el-form-item label="手机号" label-width="80">
            <el-input
              v-model.trim="queryForm.condition.phone"
              clearable
              placeholder="请输入手机号"
            />
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-search" type="primary" @click="queryData">
              查询
            </el-button>
          </el-form-item>
        </el-form>
      </vab-query-form-right-panel>
    </vab-query-form>

    <el-table
      v-loading="listLoading"
      border
      :data="list"
      @selection-change="setSelectRows"
    >
      <el-table-column align="center" label="编号" width="55">
        <template #default="{ $index }">
          {{ $index + 1 }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="账号" prop="account" />
      <el-table-column align="center" label="手机号" prop="phone" />
      <el-table-column align="center" label="昵称" prop="nickName" />
      <el-table-column align="center" label="邮箱" prop="email" />
      <el-table-column align="center" label="状态" prop="isEnable">
        <template #default="{ row }">
          <el-switch
            v-model="row['isEnable']"
            :active-value="1"
            :disabled="isChanging"
            :inactive-value="0"
            @change="changeStatus(row)"
          />
        </template>
      </el-table-column>
      <el-table-column align="center" label="部门名称" prop="deptName">
        <template #default="{ row }">
          <span>{{ row['deptName'] || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="操作"
        show-overflow-tooltip
        width="85"
      >
        <template #default="{ row }">
          <el-dropdown>
            <span class="el-dropdown-link">
              操作
              <i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>
                <el-button type="text" @click="resetPassword(row)">
                  重置密码
                </el-button>
              </el-dropdown-item>
              <el-dropdown-item>
                <el-button type="text" @click="assignRole(row)">
                  分配角色
                </el-button>
              </el-dropdown-item>
              <el-dropdown-item>
                <el-button type="text" @click="assignDept(row)">
                  分配部门
                </el-button>
              </el-dropdown-item>
              <el-dropdown-item>
                <el-button type="text" @click="handleEdit(row)">修改</el-button>
              </el-dropdown-item>
              <el-dropdown-item>
                <el-button type="text" @click="handleDelete(row)">
                  删除
                </el-button>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
      <template #empty>
        <el-image
          class="vab-data-empty"
          :src="require('@/assets/empty_images/data_empty.png')"
        />
      </template>
    </el-table>
    <el-pagination
      background
      :current-page="queryForm.pageNum"
      :layout="layout"
      :page-size="queryForm.pageSize"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />
    <edit ref="edit" @fetch-data="fetchData" />
    <role-assign ref="roleEdit" />
    <dept-assign ref="deptEdit" @fetch-data="fetchData" />
  </div>
</template>

<script>
  import { doDelete, getList, updateUserStatus } from '@/api/userManagement'
  import { resetPassword } from '@/api/user'
  import Edit from './components/UserManagementEdit'
  import RoleAssign from '@/views/setting/userManagement/components/RoleAssign'
  import DeptAssign from '@/views/setting/userManagement/components/DeptAssign'
  import { mapGetters } from 'vuex'

  export default {
    name: 'UserManagement',
    components: { DeptAssign, RoleAssign, Edit },
    filters: {
      statusFilter(status) {
        const statusMap = {
          1: 'success',
          0: 'error',
        }
        return statusMap[status]
      },
    },
    data() {
      return {
        list: [],
        listLoading: true,
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        selectRows: '',
        isChanging: false,
        queryForm: {
          pageNum: 1,
          pageSize: 10,
          condition: {
            orderBy: 'id',
            orderDirect: 'desc',
            phone: null,
            account: null,
          },
        },
      }
    },
    computed: {
      ...mapGetters({
        sexType: 'dict/sexTypeJson',
      }),
    },
    created() {
      this.fetchData()
    },
    methods: {
      changeStatus(row) {
        if (row.id === undefined || row.id === '' || row.id === null) {
          return
        }
        const newState = row.isEnable
        const initState = row.isEnable === 1 ? 0 : 1
        this.isChanging = true
        updateUserStatus(row.id, newState)
          .then((res) => {
            if (res && res.status === 0) {
              this.$baseMessage(
                '状态修改成功！',
                'success',
                'vab-hey-message-success'
              )
            } else {
              this.$baseMessage(
                res ? res.msg : '修改失败！',
                'error',
                'vab-hey-message-error'
              )
              row['isEnable'] = initState
            }
          })
          .catch((e) => {
            console.log(e)
            row['isEnable'] = initState
            this.$baseMessage(
              e ? e.message : '操作失败！',
              'error',
              'vab-hey-message-error'
            )
          })
          .then(() => {
            this.isChanging = false
          })
      },
      resetPassword(row) {
        this.$baseConfirm('你确定要重置当前密码吗', null, async () => {
          try {
            const res = await resetPassword({ id: row.id })
            if (res && res.status === 0) {
              this.$baseMessage(
                '用户[' + row.nickName + ']重置密码成功',
                'success',
                'vab-hey-message-success'
              )
              await this.fetchData()
            } else {
              this.$baseMessage(
                res ? res.msg : '操作失败！',
                'error',
                'vab-hey-message-error'
              )
            }
          } catch (e) {
            console.log(e)
            this.$baseMessage(
              e ? e.message : '操作失败！',
              'error',
              'vab-hey-message-error'
            )
          }
        })
      },
      assignRole(row) {
        console.log(row)
        this.$refs['roleEdit'].showEdit(row)
      },
      assignDept(row) {
        console.log(row)
        this.$refs['deptEdit'].showEdit(row)
      },
      setSelectRows(val) {
        this.selectRows = val
      },
      handleEdit(row) {
        if (row.id) {
          this.$refs['edit'].showEdit(row)
        } else {
          this.$refs['edit'].showEdit()
        }
      },
      handleDelete(row) {
        if (row.id) {
          this.$baseConfirm('你确定要删除当前项吗', null, async () => {
            try {
              const res = await doDelete(row.id)
              if (res && res.status === 0) {
                this.$baseMessage(
                  '删除成功！',
                  'success',
                  'vab-hey-message-success'
                )
                await this.fetchData()
              } else {
                this.$baseMessage(
                  res ? res.msg : '删除失败！',
                  'error',
                  'vab-hey-message-error'
                )
              }
            } catch (e) {
              console.log(e)
              this.$baseMessage(
                e ? e.message : '删除失败！',
                'error',
                'vab-hey-message-error'
              )
            }
          })
        } else {
          if (this.selectRows.length > 0) {
            const ids = this.selectRows.map((item) => item.id).join()
            this.$baseConfirm('你确定要删除选中项吗', null, async () => {
              const { msg } = await doDelete({ ids })
              this.$baseMessage(msg, 'success', 'vab-hey-message-success')
              await this.fetchData()
            })
          } else {
            this.$baseMessage('未选中任何行', 'error', 'vab-hey-message-error')
          }
        }
      },
      handleSizeChange(val) {
        this.queryForm.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.queryForm.pageNum = val
        this.fetchData()
      },
      queryData() {
        this.queryForm.pageNum = 1
        this.fetchData()
      },
      async fetchData() {
        this.listLoading = true
        try {
          const res = await getList(this.queryForm)
          if (res && res.data) {
            const { list, total } = res.data
            this.list = list
            this.total = total
          }
        } catch (e) {
          console.log(e)
        }
        this.listLoading = false
      },
    },
  }
</script>
